import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieTestServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建Cookie对象
        Cookie cookie1 = new Cookie("username", "zhangsan");
        Cookie cookie2 = new Cookie("pass", "zhangsan");

        // 设置Cookie的关联路径
//        System.out.println(request.getContextPath());
//        cookie1.setPath(request.getContextPath() + "/king/110");
//        cookie2.setPath(request.getContextPath() + "/king/110");

        // 设置Cookie的有效期
        cookie1.setMaxAge(60 * 60 * 24);  // 设置有效期为一天
        cookie2.setMaxAge(60 * 60);  // 设置有效期为一个小时

        // 将Cookie对象发送给浏览器客户端
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        // 此时这两个cookie保存在硬盘中
    }
}
